<script setup>
import { ref, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import http from '@/utils/api.js';
import router from "@/Router/index.js"; // 自定义的 HTTP 请求工具

const route = useRoute(); // 用于获取路由参数

// 定义 userId
const userId = ref(route.query.id); // 从路由中获取用户 ID

// 用户信息数据
const userInfo = ref({
  id: '',
  username: '',
  password: '',
  email: '',
  phone: '',
  gender: '',
  profile: '' // 存储 Base64 编码的头像图片
});

// 图片选择
const profileImage = ref(null); // 用于存储选择的图片文件
async function loadProductDetails() {
  const productId = route.query.id; // 使用 route 获取 query 参数中的 id
  try {
    const response = await http.get(`/product/id/${productId}`);  // 根据 id 获取商品详情
    console.log(response.data);
    if (response.data) {
      product.value = response.data;  // 将返回的商品数据保存到 product 中
    } else {
      console.error("商品未找到");
    }
  } catch (error) {
    console.error("加载商品详情失败:", error);
  }
}

// 加载用户详情
const loadUserDetails = async () => {
  try {
    const response = await http.get(`/user/id/${userId.value}`);
    console.log('返回的数据:', response);
    if (response.code === 200) {
      userInfo.value = response.data;
    } else {
      console.error('用户未找到:', response.message);
    }
  } catch (error) {
    console.error('加载用户详情失败:', error);
  }
};

// 图片上传并转换为 Base64
const handleImageUpload = (event) => {
  const file = event.target.files[0];
  if (file) {
    // 校验文件大小（2MB）
    if (file.size > 2 * 1024 * 1024) {
      alert('图片大小不能超过 2MB');
      return;
    }

    // 校验文件类型
    const validTypes = ['image/jpeg', 'image/png', 'image/gif'];
    if (!validTypes.includes(file.type)) {
      alert('只支持 JPEG/PNG/GIF 格式的图片');
      return;
    }

    const reader = new FileReader();
    reader.onloadend = () => {
      userInfo.value.profile = reader.result; // 保存 Base64 编码的图片
    };
    reader.readAsDataURL(file); // 将图片转换为 Base64
  }
};

// 校验表单
const validateForm = () => {
  if (!userInfo.value.username) return '用户名不能为空';
  if (!userInfo.value.password) return '密码不能为空';
  if (!userInfo.value.email) return '邮箱不能为空';
  if (!userInfo.value.phone) return '电话不能为空';
  if (!userInfo.value.gender) return '性别不能为空';
  return null; // 校验通过
};

// 提交表单
const handleSubmit = async () => {
  console.log("id:" + userId.value)
  const payload = {
    id: userId.value, // 使用全局定义的 userId
    username: userInfo.value.username,
    password: userInfo.value.password,
    email: userInfo.value.email,
    phone: userInfo.value.phone,
    gender: userInfo.value.gender,
    profile: userInfo.value.profile,
  };

  console.log('提交的数据:', payload); // 打印提交的数据
  try {
    const response = await http.post('/user/update', payload);
    if (response.code === 200) {
      console.log('提交成功:', response);
      alert('用户信息更新成功');
      router.push('/dashboard');
    } else {
      console.error('提交失败:', response.message);
      alert(`提交失败: ${response.message}`);
    }
  } catch (error) {
    console.error('提交失败:', error);
    alert('提交失败，请稍后再试');
  }
};

// 页面加载时获取用户详情
onMounted(() => {
  loadUserDetails();
});
</script>

<template>
  <div class="form-container">
    <el-form :model="userInfo" label-width="120px" class="user-form">
      <el-form-item label="用户名">
        <el-input v-model="userInfo.username" placeholder="请输入用户名"/>
      </el-form-item>
      <el-form-item label="密码">
        <el-input v-model="userInfo.password" type="password" placeholder="请输入密码"/>
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="userInfo.email" placeholder="请输入邮箱"/>
      </el-form-item>
      <el-form-item label="电话">
        <el-input v-model="userInfo.phone" placeholder="请输入电话"/>
      </el-form-item>
      <el-form-item label="性别">
        <el-select v-model="userInfo.gender" placeholder="请选择性别">
          <el-option label="男" value="male"/>
          <el-option label="女" value="female"/>
        </el-select>
      </el-form-item>
      <el-form-item label="头像">
        <input type="file" @change="handleImageUpload" class="image-upload"/>
        <div class="avatar-preview">
          <img
              v-if="userInfo.profile"
              :src="userInfo.profile"
              alt="Profile Image"
              class="profile-img"
          />
          <div v-else class="no-avatar">未上传头像</div>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped>
.form-container {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  background-color: #fff;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
}

.user-form {
  width: 100%;
}

.el-form-item {
  margin-bottom: 15px;
}

.image-upload {
  display: block;
  margin-top: 10px;
}

.avatar-preview {
  display: flex;
  align-items: center;
  margin-top: 10px;
}

.profile-img {
  max-width: 100px;
  max-height: 100px;
  margin-right: 15px;
  border: 1px solid #ddd;
  border-radius: 8px;
  object-fit: cover;
}

.no-avatar {
  color: gray;
}

.el-button {
  width: 100%;
  padding: 10px 0;
  font-size: 16px;
  background-color: #409EFF;
  border-color: #409EFF;
  color: white;
}
</style>
